package com.zxt.example.config.mvc;

import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 */
@RestControllerAdvice
public class MvcDataBinderAdvice {

    /**
     * 数据绑定器, 从请求中获取的字符串参数时“2018-09-06 12:24:56”如何绑定为Data类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new CustomDateEditor());
    }


    /**
     * 自定义的DateEditor转换
     */
    public static class CustomDateEditor extends PropertyEditorSupport {
        private final DateTimeFormatter dateFormat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        private final DateTimeFormatter dateFormat2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        @Override
        public void setAsText(@Nullable String text) {
            if (!StringUtils.hasText(text) || text.contains("NaN")) {
                this.setValue(null);
            } else {
                try {
                    this.setValue(LocalDateTime.parse(text, dateFormat1));
                } catch (DateTimeParseException e1) {
                    try {
                        this.setValue(LocalDateTime.parse(text, dateFormat2));
                    } catch (DateTimeParseException e2) {
                        throw new IllegalArgumentException("Could not parse date: " + e2.getMessage(), e2);
                    }
                }
            }
        }
    }
}
